Easy2Siksha.com
2. What is an abstract class ? How do we create one?
Ans: What Is an Abstract Class?
In object-oriented programming (OOP), an abstract class is a class that cannot be
instantiated directly. In other words, you cannot create objects from it. Instead, it serves as
a blueprint for other classes.
An abstract class usually contains at least one pure virtual function—a function that has no
body and must be implemented by derived (child) classes.
Think of it like a contract: the abstract class says, “Any class that inherits from me must
provide its own version of these functions.”
Everyday Analogy
Imagine a school. There’s a general concept of a Teacher. But you don’t hire a “generic
teacher”—you hire a Math Teacher, Science Teacher, or English Teacher.
The abstract class is like the idea of “Teacher.” It defines what all teachers must be able to
do (teach, give assignments, grade students), but it doesn’t specify how. Each subject
teacher (derived class) fills in the details.
So, the abstract class sets the rules, and the child classes provide the actual implementation.
Why Do We Need Abstract Classes?
Abstract classes are important because they:
1. Provide a blueprint: They define what functions must exist in derived classes.
2. Encourage consistency: All child classes follow the same structure.
3. Support polymorphism: You can use pointers or references to the abstract class to
work with different derived classes in a uniform way.
4. Separate design from implementation: The abstract class focuses on “what” needs
to be done, while derived classes focus on “how” it’s done.
How Do We Create an Abstract Class in C++?
In C++, an abstract class is created by declaring at least one pure virtual function.
A pure virtual function is written like this:
virtual void functionName() = 0;
The = 0 means the function has no body—it’s just a declaration.
Example: Abstract Class in C++